<template>
    <view class="partner-manage position-r">

        <view class="partner-manage__header  mr-v-24 position-r">
            <view class="border8 pd-l-24 bg-white">
                <u--form
                    labelWidth="120"
                    labelPosition="left"
                    :model="form"
                    ref="uForm"
                >
                    <u-form-item
                        label="合作伙伴名称"
                        prop="nickName"
                        borderBottom
                    >
                        <u--input
                            v-model.trim="form.nickName"
                            border="none"
                            color="#B3ADAE"
                            :customStyle="{padding:'12rpx 0'}"
                            placeholder="请输入合作伙伴名称"
                            @input="search"
                        ></u--input>
                    </u-form-item>
                </u--form>
            </view>
            
        </view>
          
        
          
        <view class="partner-manage__body mr-v-24">
            <view class="shop-item border8 pd-v-24 bg-white mr-t-20 full-w" v-for="(item,index) in list" :key="'check'+index">
                <view class="shop-item__body pd-t-32 pd-b-24 border-b">
                    <view class="font26 lh-28 bold color-default">
                        {{item.nickName}}
                    </view>
                    
                    <view class="mr-t-40 flex flex-center">
                        <view class="desc font24 lh-28 color-note mr-r-36">账号</view>
                        <view class="note flex-1 font24 lh-28 color-default flex flex-center">
                            {{item.userName}}

                            <u-button plain size="mini" :customStyle="{height:'46rpx',marginLeft:'16rpx',width:'112rpx'}" shape="circle" color="#2B9951"  text="重置密码"  @click="resetPwd(item)"></u-button>
                        </view>
                    </view>
                    
                    
                    <view class="mr-t-40 flex flex-center">
                        <view class="desc font24 lh-28 color-note mr-r-36">钱包余额</view>
                        <view class="note flex-1 font24 lh-28 color-default flex flex-center">
                            ¥{{item.walletBalance}}

                            <u-button plain size="mini" :customStyle="{height:'46rpx',marginLeft:'16rpx',width:'112rpx'}" shape="circle" color="#2B9951"  text="扣除金额" @click="setBalanceShow(item)"></u-button>
                        </view>
                    </view>
                    
                    <view class="mr-t-40 flex flex-center">
                        <view class="desc font24 lh-28 color-note mr-r-36">账号状态</view>
                        <view class="note flex-1 font24 lh-28 color-default flex flex-center">
                            <u-switch activeColor="#35BE65" size="15" v-model="item.status" activeValue="0" inactiveValue="1" @change="statusChange(item)"></u-switch>
                        </view>
                    </view>
                    
                    <view class="mr-t-40 flex flex-center">
                        <view class="desc font24 lh-28 color-note mr-r-36">是否可提现</view>
                        <view class="note flex-1 font24 lh-28 color-default flex flex-center">
                            <u-switch activeColor="#35BE65" size="15" v-model="item.isWithdrawal" activeValue="1" inactiveValue="0" @change="withdrawalChange(item)"></u-switch>
                        </view>
                    </view>
                    
                    <view class="mr-t-40 flex flex-center">
                        <view class="desc font24 lh-28 color-note mr-r-36">分佣比例</view>
                        <view class="note flex-1 font24 lh-28 color-default flex flex-center">
                            {{item.sharingRatio || 0}}%
                        </view>
                    </view>
                    
                </view>

                <view class="shop-item__footer pd-h-16 pd-v-24 flex flex-center">
                    <view class="flex-1"></view>
                        <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="删除"  @click="deleteItem(item,index)"></u-button>

                        <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="修改" @click="editItem(item,index)"></u-button>

                        <u-button plain :customStyle="{height:'60rpx',marginLeft:'16rpx',width:'152rpx'}" shape="circle" color="#35BE65"  text="数据概览" @click="partnerPreview(item)"></u-button>


                </view>
                
                
            </view>
        </view>


        <view class="partner-manage__footer position-f flex flex-j-center flex-center full-w">
            <u-button :customStyle="{height:'88rpx',width:'600rpx'}" shape="circle" color="#35BE65"  text="新增合作伙伴" @click="add"></u-button>
        </view>
          
          
        <u-overlay :show="isBalanceShow" @click="setBalanceHide">
            <view class="full-w full-h flex flex-center flex-j-center">
                <view class="bg-white pd-v-40 pd-h-40 border8"  @tap.stop>
                    <view class="font32 lh-38 color-default txt-center bold">扣除金额</view>
                    <u--form class="full-w full-h" :rules="balanceRules" :model="balanceForm" ref="balanceFormRef" labelWidth="100" labelPosition="left">
                        <u-form-item label="钱包余额"> 
                            {{ activeItem.walletBalance }}
                        </u-form-item>
                        <u-form-item label="扣除金额" prop="amount"> 
                            <u-input 
                                :customStyle="{padding:'8rpx 8rpx'}"
                                fontSize="24rpx" 
                                v-model="balanceForm.amount" 
                                placeholder="请输入扣除金额" >
                            </u-input>
                        </u-form-item>

                    </u--form>
                    <div class="flex flex-center pd-t-20 flex-j-center">
                        <u-button  shape="circle" :customStyle="{height:'66rpx',width:'220rpx;'}" color="#35BE65"  text="确认" @click="setBalance"></u-button>
                    </div>
                </view>
            </view>
        </u-overlay>
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { onLoad, onReady, onShow,onReachBottom } from '@dcloudio/uni-app';
import { cooperativePartnerList,cooperativePartnerDelete,agentAndPartnerCommonChangeStatus,agentAndPartnerCommonChangeIsWithdrawal,agentAndPartnerCommonDeductBalance,agentAndPartnerCommonResetPwd } from '@/api/proxy.js'


const store = useStore();
const form = ref({
    nickName: '',
});


const uform = ref(null);
const timer = ref(null);
const addPopupShow = ref(false);
const switchValue = ref(false);
const list = ref([])
const total = ref(0);
const params = ref({
    pageNum: 1,
    pageSize: 10
})
const isBalanceShow = ref(false);
const balanceForm = ref({
    amount: ''
});

const balanceRules = ref({
  amount: [
        {
            required: true,
            message: '请输入扣除金额',
            trigger: ['blur','change'],
            validator(rule, value, callback) {
                if (!value || value == 0) {
                    callback('请输入扣除金额');
                    return false;
                }
                let isNumberReg = /^\d+(\.\d{1,2})?$/

                if(!isNumberReg.test(value)) {
                    callback('请输入正确的扣除金额');
                    return false;
                }

                if(value > activeItem.value.walletBalance) {
                    callback('扣除金额不能大于钱包余额');
                    return false;
                }
 
                return true;
            }
        }
    ],
})

const activeItem = ref({});
const balanceFormRef = ref(null)

onReady(() => {
    
})

onShow(() => {
    
})

onLoad(() => {
    getCooperativePartnerList()

})


onReachBottom(() => {
    if(list.value.length < total.value) {
        params.value.pageNum++;
        getCooperativePartnerList()
    }
})


const resetPwd = (item) => {
    uni.showModal({
        title: '警告',
        content: '确定要重置该商户密码吗？',
        success: (res) => {
            if (res.confirm) {
                uni.showLoading({
                    title: '加载中'
                })
                agentAndPartnerCommonResetPwd({
                    userId: item.userId,
                    password:'123456'
                }).then(res => {
                    uni.hideLoading()
                    if(res.code == 200) {
                        uni.showToast({
                            title: '重置成功',
                            icon:'none'
                        })
                        //
                    } else {
                        uni.showToast({
                           title: res.msg,
                           icon:'none'
                        })

                    }
                }).catch(err => {
                    uni.hideLoading()
                    uni.showToast({
                        title: '重置失败',
                        icon:'none'
                    })

                })
                
            }
        }
    })
}

const setBalanceShow = (item) => { 
    isBalanceShow.value = true;
    activeItem.value = item;
    balanceForm.value = {
        amount: '0'
    }
    setBalanceRules()
}

const setBalanceHide = () => { 
    isBalanceShow.value = false
}


const setBalanceRules = () => {
    balanceFormRef.value.setRules(balanceRules.value);
}



const setBalance = (item) => { 
    balanceFormRef.value.validate().then(res => {
        if(res) {
            uni.showModal({
                title: '警告',
                content: '确定要扣除该合作伙伴余额吗？',
                success: (res) => {
                    if (res.confirm) {
                        uni.showLoading({
                            title: '扣除中...',
                            mask: true
                        })
                        
                        agentAndPartnerCommonDeductBalance({
                            userId: activeItem.value.userId,
                            status: 0,
                            amount: balanceForm.value.amount
                        }).then(res => {
                            if(res.code == 200) {
                                uni.showToast({
                                    title: '扣除成功',
                                    icon:'none'
                                })
                                activeItem.value.walletBalance = parseFloat((activeItem.value.walletBalance - balanceForm.value.amount).toFixed(2))
                                setBalanceHide()
                                //
                            } else {
                                uni.showToast({
                                title: res.msg,
                                icon:'none'
                                })

                            }

                        }).catch(err => {
                            uni.showToast({
                                title: '扣除失败',
                                icon:'none'
                            })
                        })
                    }
                }
            });
        }
    })
    
}

const withdrawalChange = (item) => { 
    agentAndPartnerCommonChangeIsWithdrawal({
        userId: item.userId,
        isWithdrawal: item.isWithdrawal
    }).then(res => {
        if(res.code == 200) {
            uni.showToast({
                title: '修改成功',
                icon:'none'
            })
            //
        } else {
            uni.showToast({
               title: res.msg,
            })
            item.isWithdrawal = item.isWithdrawal == '0' ? '1' : '0'
        }
    }).catch(err => {
        item.isWithdrawal = item.isWithdrawal == '0' ? '1' : '0'
        uni.showToast({
            title: '修改失败',
            icon:'none'
        })
    })
}

const statusChange = (item) => {
    console.log(item)
    agentAndPartnerCommonChangeStatus({
        userId: item.userId,
        status: item.status
    }).then(res => {
        if(res.code == 200) {
            uni.showToast({
                title: '修改成功',
                icon:'none'
            })
            //
        } else {
            uni.showToast({
                title: res.msg,
                icon:'none'
            })
            item.status = item.status == '0' ? '1' : '0'
        }
    }).catch(err => {
        item.status = item.status == '0' ? '1' : '0'
        uni.showToast({
            title: '修改失败',
            icon:'none'

        })
    })
}
const getCooperativePartnerList = () => {
    cooperativePartnerList({
        ...params.value,
        ...form.value
    }).then(res => {
        list.value = [...list.value, ...res.rows]
        total.value = res.total
    })
}

const search = () => {
    clearTimeout(timer.value);
    timer.value = setTimeout(() => {
        list.value = [];
        params.value.pageNum = 1;
        getCooperativePartnerList()
    },1000)
}


const partnerPreview = (item) => {
    uni.navigateTo({
        url: '/sub_proxy/pages/partnerPreview/partnerPreview?id='+item.userId
    })
}

const editItem = (item) => {
    uni.navigateTo({
        url: '/sub_proxy/pages/partnerAdd/partnerAdd?id=' + item.userId
    })
}


const deleteItem = (item,index) => { 
    uni.showModal({
        title: '提示',
        content: '确定删除吗？',
        success: function (res) {
            if (res.confirm) {
              cooperativePartnerDelete({userId:item.userId}).then(res => {
                    if(res.code == 200) {
                        list.value.splice(index,1)
                        uni.showToast({
                            title: '删除成功',
                            icon: 'none'
                        })
                    }else {
                              uni.showToast({
                                  title: res.msg,
                                  icon: 'none'
                              })
                          }
                })
            }
        }
    })
}

const add = () => {
    uni.navigateTo({
        url: '/sub_proxy/pages/partnerAdd/partnerAdd'
    })
}


</script>

<style scoped lang="scss">
.partner-manage {
    background: #F7F7F7;
    min-height:100vh;

    .partner-manage__header {
        
    }

    .partner-manage__body {
        padding-bottom:256rpx;

        .shop-item {
            .desc {
                width:130rpx;
            }

            .border-b {
                border-bottom:1px solid #EEEEEE;
            }
        }
    }

    .partner-manage__footer {
        left:0;
        bottom:76rpx;
    }
}
</style>
